$(function(){
	var laststamp = 0;

	var $containerbox = $("#sections");
	function addMore(){
		if(this != window){
			var offset = $(this).offset().top;
		}
		$.ajax({
			url: 'ajax_main.php',
			type: 'POST',
			dataType: 'json',
			data: {
				last: laststamp,
			},
			async: false,
		})
		.success(function(data, status, jqxhr){
			laststamp += data.length;
			xhr = jqxhr;
			for(var index=0; index<data.length; index++){
				var contents = data[index];
				var section = '<section class="section item col'+contents.col+' round shadow">';
				section += '<a href="'+contents.link+'"><h2>'+contents.title+'</h2></a>';
				if(contents.image != null){
					section += '<img alt="contentimg" title="contentimg" src="data:;base64,'+contents.image+'"/>';
				}
				section += '<p>'+contents.content+'</p>';
				section += '<date pubdate>'+contents.timestamp+'</date>';
				section += '</section>';
				var $tag = $(section);
				$("#sections").append($tag);
				$("#sections").masonry('appended', $tag);
			}

			//for pjax
			var data = {
				url: '/',
				title: "Kai6's Blog",
				content: $(".container").html(),
			};
			history.replaceState(data, data.title, data.url);
			if(this != window){
				$("html, body").animate({'scrollTop': offset}, 'slow');
			}
		});
	}

	$containerbox.masonry({
		itemSelector: '.item',
		columnWidth: 346,
		gutterWidth: 20,
	});

	//pjax
	$(window).bind('popstate', function(event){
		var data = event.originalEvent.state;
		drawHTML(data, false);
	});

	//scroll handler for infintie scroll
	/*
	$(window).scroll(function(){
	if($(window).scrollTop() == $(document).height() - $(window).height()){
	addMore();
	}
	});
	*/
	$("#readmorebutton").click(addMore);
	addMore();
});
